<template>
  <div class="scan-container">
    <div id="reader" class="scan-reader"></div>
    <div v-if="result" class="scan-result">
      <h3>扫码结果：</h3>
      <div class="scan-result-text">{{ result }}</div>
    </div>
    <button @click="startScan" class="scan-btn">重新扫码</button>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Html5Qrcode } from 'html5-qrcode'

const result = ref('')
let html5Qr = null

const startScan = () => {
  result.value = ''
  if (html5Qr) {
    html5Qr.start(
      { facingMode: "environment" },
      { fps: 10, qrbox: 250 },
      (decodedText) => {
        result.value = decodedText
        html5Qr.stop()
      },
      (errorMessage) => {
        // 可选：处理扫描错误
      }
    )
  }
}

onMounted(() => {
  html5Qr = new Html5Qrcode("reader")
  startScan()
})

onBeforeUnmount(() => {
  if (html5Qr) {
    html5Qr.stop().catch(() => {})
    html5Qr.clear()
  }
})
</script>

<style>
.scan-container {
  padding: 16px;
}
.scan-reader {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}
.scan-result {
  margin-top: 20px;
}
.scan-result-text {
  word-break: break-all;
}
.scan-btn {
  margin-top: 20px;
  padding: 8px 20px;
  font-size: 16px;
  border: none;
  background: #409eff;
  color: #fff;
  border-radius: 4px;
  cursor: pointer;
}
.scan-btn:active {
  background: #337ecc;
}
</style>

